#include "thread_pool.h"
#include "elog.h"
#include "elog_file.h"


ThreadPool* ThreadPool::pinstance_ = nullptr;
std::mutex ThreadPool::singleton_mutex_;

ThreadPool::ThreadPool(int thread_count) : stop_(false) {
    // 创建指定数量的线程并加入到线程池中
    for (size_t i = 0; i < thread_count; ++i) {
        workers_.emplace_back(
            [this] {
                for (;;) {
                    std::function<void()> task;
                    {
                        std::unique_lock<std::mutex> lock(this->queue_mutex_);
                        this->condition_.wait(lock, [this] { return this->stop_ || !this->tasks_.empty(); });
                        if (this->stop_ && this->tasks_.empty()) {
                            return;
                        }
                        task = std::move(this->tasks_.front());
                        this->tasks_.pop();
                    }
                    task();
                }
            }
        );
    }
}

ThreadPool::~ThreadPool() {
    std::unique_lock<std::mutex> lock(queue_mutex_);
    log_i("destroy threadpool");
    stop_ = true;
    condition_.notify_all();
    for (std::thread& worker : workers_) {
        worker.join();
    }
    
    delete pinstance_;
}

ThreadPool* ThreadPool::GetInstance(int thread_count) {
    std::lock_guard<std::mutex> lock(singleton_mutex_);
    if (pinstance_ == nullptr) {
        pinstance_ = new ThreadPool(thread_count);
    }
    return pinstance_;
}
